package com.hlf.modules.wechat.service.impl;

import com.hlf.common.constants.Constants;
import com.hlf.common.exception.BusinessException;
import com.hlf.common.utils.IdWorkerFactory;
import com.hlf.common.utils.PropertieUtil;
import com.hlf.common.utils.wx.WeixinOauth2Token;
import com.hlf.common.utils.wx.WxUserInfo;
import com.hlf.common.utils.wx.WxUtils;
import com.hlf.modules.api.service.CartService;
import com.hlf.modules.merchant.order.entity.Order;
import com.hlf.modules.merchant.order.mapper.OrderMapper;
import com.hlf.modules.merchant.order.service.OrderService;
import com.hlf.modules.merchant.store.entity.Store;
import com.hlf.modules.merchant.store.service.StoreService;
import com.hlf.modules.merchant.table.entity.Table;
import com.hlf.modules.merchant.table.service.TableService;
import com.hlf.modules.sys.service.SysUserTokenService;
import com.hlf.modules.wechat.mapper.CustomerMapper;
import com.hlf.modules.wechat.model.Customer;
import com.hlf.modules.wechat.service.CustomerService;
import com.hlf.modules.wechat.service.WeChatService;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;

/**
 * Created by Administrator on 2017/12/13.
 */
@Service
public class WeChatServiceImpl implements WeChatService {

    @Autowired
    private TableService tableService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private SysUserTokenService sysUserTokenService;
    @Autowired
    private StoreService storeService;
    @Autowired
    private PropertieUtil propertieUtil;
    @Autowired
    private CartService cartService;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderMapper orderMapper;

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Transactional
    @Override
    public Map<String, Object> Oauth2Logo(String tableId, String code) {

        String endUrl = propertieUtil.getPropertie("FRONT_END_URL");

        Map<String, Object> map = new HashedMap();
        Long tableIdL = Long.parseLong(tableId);
        //先获取微信认证信息
        WeixinOauth2Token oauth2AccessToken = WxUtils.getOauth2AccessToken(1L, code);
        Table table = tableService.queryObjectForId(tableIdL);
        if (table == null) {
            throw new BusinessException("抱歉,该餐桌已被删除!");
        }

        Store store = storeService.queryObject(table.getStoreId());
        Byte softwareStatus = store.getSoftwareStatus();
        if (Constants.SOFTWARE_PAY_STATUS_TRY_EXPIRE.equals(softwareStatus) ||
                Constants.SOFTWARE_PAY_STATUS_PAY_EXPIRE.equals(softwareStatus)) {
            logger.info("门店未开启扫码点餐功能!");
            map.put("redirect", endUrl+"/#/index");
            return map;
        }

        //多次扫码
        String openId = oauth2AccessToken.getOpenId();
        Customer customer = customerService.queryByOpenId(openId);
        Table tableByCust = null;
        //当前消费餐桌与扫码的餐桌是否同一个

        if (customer != null && tableIdL.equals(customer.getSpendTableId())) {
            tableByCust = tableService.queryObjectForId(customer.getSpendTableId());
        }

        //先检查餐桌状态
        Byte tableStatus = table.getTableStatus();
        if (Constants.TABLE_STATUS_ORDER.equals(tableStatus)) {
            long diff = System.currentTimeMillis() - table.getLastUpdateDate().getTime();
            int minutes = (int) (diff / (1000 * 60));
            //点餐中
            if (minutes > Integer.parseInt(propertieUtil.getPropertie("ORDER_FOOD_MAX_MIN"))) {
                logger.info("用户长时间未点餐,释放餐桌!");
                //更改状态,清空购物车
                cartService.deleteCartByTableId(tableIdL);
                table.setTableStatus(Constants.TABLE_STATUS_FREE);
                table.setLastUpdateDate(new Date());
                tableService.updateByPrimaryKeySelective(table);
            } else if (tableByCust != null) {
                //进入未完成,继续点餐
                cartService.deleteCartByTableId(tableIdL);
                table.setLastUpdateDate(new Date());
                tableService.updateByPrimaryKeySelective(table);
                map = sysUserTokenService.createToken(customer.getCustomerId());
                map.put("redirect", endUrl+"/#/dinernumber");
                return map;
            } else {
//                throw new BusinessException("抱歉,当前餐桌已有人使用!");
                map.put("redirect", endUrl+"/#/a");
                return map;
            }
        }else if (Constants.TABLE_STATUS_USE.equals(tableStatus)) {
            //就餐时
            if (tableByCust != null) {

                //查处未付款订单
                Order order = orderService.queryOrderBytableId(tableId);
                long diff = System.currentTimeMillis() - order.getInsertDate().getTime();
                int minutes = (int) (diff / (1000 * 60));

                if (minutes > Integer.parseInt(propertieUtil.getPropertie("ORDER_FOOD_MAX_MIN"))) {
                    logger.info("用户长时间未点餐,释放餐桌!");
                    //更改状态,清空购物车
                    cartService.deleteCartByTableId(tableIdL);
                    orderService.cancelOrder(customer,String.valueOf(order.getId()));
                    map = sysUserTokenService.createToken(customer.getCustomerId());
                    map.put("redirect", endUrl+"/#/dinernumber");
                    return map;
                }else {
                    //返回token
                    map = sysUserTokenService.createToken(customer.getCustomerId());
                    map.put("redirect", endUrl+"/#/OrderConfirm");
                    return map;
                }
            } else {
//                throw new BusinessException("抱歉,当前餐桌已有人使用!");
                map.put("redirect", endUrl+"/#/a");
                return map;
            }
        } else if (!Constants.TABLE_STATUS_FREE.equals(tableStatus)) {
//            throw new BusinessException("抱歉,当前餐桌已有人使用!");
            map.put("redirect", endUrl+"/#/a");
            return map;
        }

        //用户信息
        WxUserInfo userInfo = WxUtils.getOauth2WxUserInfo(oauth2AccessToken.getOpenId(), oauth2AccessToken.getAccessToken());
        if (userInfo == null) {
            logger.error("获取微信用户信息失败！");
        }
        if (customer == null) {
            customer = new Customer();
            customer.setCustomerId(IdWorkerFactory.nextId());
            customer.setSpendStoreId(table.getStoreId());
            customer.setSpendTableId(tableIdL);
            customerService.insert(userInfo, customer);
        } else {
            customer.setSpendTableId(tableIdL);
            customer.setSpendStoreId(table.getStoreId());
            customer.setLastUpdateDate(new Date());
            customerService.updateByOpenId(userInfo, customer);
        }
        //设置为点餐状态
        table.setTableStatus(Constants.TABLE_STATUS_ORDER);
        table.setLastUpdateDate(new Date());
        tableService.updateByPrimaryKeySelective(table);
        //生成token，并保存到数据库
        map = sysUserTokenService.createToken(customer.getCustomerId());
        map.put("redirect", endUrl+"/#/dinernumber");
        return map;
    }

}
